package com.alibaba.handler.security;

import com.alibaba.common.ResponseResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.alibaba.define.enums.AppHttpCodeEnum.*;

/**
 * @author : hanyang
 * @date : 2023-11-04 12:44
 **/
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.error("AuthenticationEntryPointImpl#commence Exception:{}", JSON.toJSONString(e));
        ResponseResult<Object> error = null;
        // 响应给前端
        if (e instanceof InsufficientAuthenticationException) {
            error = ResponseResult.error(NEED_LOGIN.getCode(), NEED_LOGIN.getMsg());
        } else if (e instanceof BadCredentialsException) {
            error = ResponseResult.error(LOGIN_ERROR.getCode(), LOGIN_ERROR.getMsg());
        } else {
            error = ResponseResult.error(SYSTEM_ERROR.getCode(), SYSTEM_ERROR.getMsg());
        }
        WebUtils.renderString(httpServletResponse, JSON.toJSONString(error));
    }
}
